#include "TcpClient.hpp"
#include "protocol.hpp"

void TerminalOut(char* buffer){
    string src_str = buffer; 
    string rsp_str;
    while(Decode(src_str,&rsp_str)){
        //成功了我们的rsp_str就是一个完整的报文
        Response rsp; //得到一个结束,打印出来
        rsp.Deserialization(rsp_str);
        rsp.Print();
    }
}
void PrintStreamFlags(){
    LOG(LogLevel::DEBUG) << cin.good();
    LOG(LogLevel::DEBUG) << cin.eof();
    LOG(LogLevel::DEBUG) << cin.fail();
    LOG(LogLevel::DEBUG) << cin.bad();
}
void Task(ClientConnection& con)
{   
    while(1){
        int x,y;
        char op;
        LOG(LogLevel::INFO) << "Please Enter# ";
        // PrintStreamFlags();
        cin >> x  >> op >> y;
        // PrintStreamFlags();
        if (cin.fail()){
            LOG(LogLevel::DEBUG) << "开始重置";
            cin.clear();
            char c;
            while(cin.get(c)){
                if (c == '\n') break;
            }
        }
        // PrintStreamFlags();
        // sleep(2);
        Request req(x,y,op);
        string req_str;
        req.Serialization(&req_str);
        //构建询问字符串
        Encode(req_str);
        LOG(LogLevel::DEBUG) << "client sending: " << req_str.size() << "byte";
        for(char c : req_str) {
            printf("%02X ", (unsigned char)c);
        }
        printf("\n");
        int n = ::send(con.Fd(),req_str.c_str(),req_str.size(),0);
        if (n > 0){
            char buffer[1024];
            int m = recv(con.Fd(),buffer,sizeof(buffer)-1,0);
            if (m > 0){
                buffer[m] = 0;
                LOG(LogLevel::INFO) << "结果字符串: " << buffer;
                TerminalOut(buffer);
            }
            else {
                con.SetStatus(Status::DISCONNECTED); //重新连接
                break;
            }
        }
        else {
            con.SetStatus(Status::CLOSED);
            return;
        }
    }
}


int main(int argc,char* argv[]){
    if (argc != 3){
        Useage(argv[0]);
        exit(Exitcode::USEAGE_ERROR);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    TcpClient client(serverip,serverport);
    client.Insert(Task);
    client.Start();
    return 0;
}